//
//  ImagePreview.m
//  etionUI
//
//  Created by wangjian on 2/12/14.
//  Copyright (c) 2014 GuangZhouXuanWu. All rights reserved.
//

#import "ImagePreview.h"
#import "ImageBrowserView.h"

#define IMAGE_MARGIN 5
#define IMAGE_CELL_REUSE_IDENTIFIER @"imageCellReuseIdentifier"

@interface CImagePreviewLayout : UICollectionViewFlowLayout

@property (nonatomic, assign) CImagePreview *imagePreview;

@end

@implementation CImagePreviewLayout

- (void)prepareLayout
{
    [super prepareLayout];
    
    if (self.imagePreview.limitImageNum == 1 && self.imagePreview.imageNum == 1)
    {
        UIImage *image = [self.imagePreview.delegate imagePreview:self.imagePreview imageAtIndex:0];
        self.itemSize = [UIImage caleFitImageSize:image.size targetSize:self.imagePreview.maxImageSize];
    }
    else
    {
        self.itemSize = self.imagePreview.minImageSize;
    }
    self.minimumInteritemSpacing = IMAGE_MARGIN;
    self.minimumLineSpacing = IMAGE_MARGIN;
}

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray* array = [super layoutAttributesForElementsInRect:rect];
    CGRect visibleRect;
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;
    
    for (UICollectionViewLayoutAttributes* attributes in array)
    {
        if (CGRectIntersectsRect(attributes.frame, rect))
        {
            if (self.imagePreview.limitImageNum == 1 && self.imagePreview.imageNum == 1)
            {
                attributes.frame = CGRectMake((rect.size.width-self.itemSize.width)/2, 0, self.itemSize.width, self.itemSize.height);
            }
        }
    }
    return array;
}

//- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
//{
//    // Must call super
//    UICollectionViewLayoutAttributes *attributes = [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];
//    
//    if (self.imagePreview.limitImageNum == 1 && self.imagePreview.imageNum == 1)
//    {
//        // only change attributes on inserted cells
//        if (!attributes)
//            attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];
//    }
//    
//    return attributes;
//}
//
//// Note: name of method changed
//// Also this gets called for all visible cells (not just the deleted ones) and
//// even gets called when inserting cells!
//- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
//{
//    // So far, calling super hasn't been strictly necessary here, but leaving it in
//    // for good measure
//    UICollectionViewLayoutAttributes *attributes = [super finalLayoutAttributesForDisappearingItemAtIndexPath:itemIndexPath];
//    
//    if (self.imagePreview.limitImageNum == 1 && self.imagePreview.imageNum == 1)
//    {
//        // only change attributes on deleted cells
//        if (!attributes)
//            attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];
//    }
//    
//    return attributes;
//}


@end

@class CImageCollectionView;
@protocol CImageCollectionViewDelegate <UICollectionViewDelegate>

- (void)imageCollectionViewSizeChange:(CImageCollectionView *)imageCollectionView;

@end

@interface CImageCollectionView : UICollectionView

@property (nonatomic, assign) id<CImageCollectionViewDelegate> delegate;

@end

@implementation CImageCollectionView

- (void)setContentSize:(CGSize)contentSize
{
    [super setContentSize:contentSize];
    [self.delegate imageCollectionViewSizeChange:self];
}

@end

@interface CImagePreview() <UICollectionViewDataSource, CImageCollectionViewDelegate, CImageBrowserViewDelegate>

@property (nonatomic, retain) CImagePreviewLayout *layout;
@property (nonatomic, retain) CImageCollectionView *collectionView;
@property (nonatomic, retain) CImageBrowserView *imageBrowserView;
@property (nonatomic, assign) UILongPressGestureRecognizer *longPressGesture;

@end

@implementation CImagePreview

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.limitImageNum = 20;
        self.growingAutomatic = YES;
        self.editable = YES;
        self.editing = NO;
        self.takeImageEnable = YES;
        
        NSUInteger colNum = frame.size.width>=300 ? frame.size.width/100 : 3;
        CGFloat minW = (NSInteger)((frame.size.width-(colNum-1)*IMAGE_MARGIN)/colNum);
        self.minImageSize = CGSizeMake(minW, minW);
        CGFloat maxW = (NSInteger)(frame.size.width/2);
        self.maxImageSize = CGSizeMake(maxW, maxW);
        
        self.layout = [[[CImagePreviewLayout alloc] init] autorelease];
        self.layout.imagePreview = self;
        
        self.collectionView = [[[CImageCollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout] autorelease];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        self.collectionView.backgroundColor = [UIColor clearColor];
        [self.collectionView registerClass:[CImagePreviewCell class] forCellWithReuseIdentifier:IMAGE_CELL_REUSE_IDENTIFIER];
        [self addSubview:self.collectionView];
    }
    return self;
}

- (void)dealloc
{
    [_layout release];
    [_collectionView release];
    [_longPressGesture release];
    [super dealloc];
}

- (void)didMoveToSuperview
{
    if (self.superview != nil)
    {
        [super didMoveToSuperview];
        [self reloadImages];
    }
}

- (void)reloadImages
{
    [self.collectionView reloadData];
}

- (NSUInteger)imageNum
{
    return [self.delegate numberOfImagesForImagePreview:self];
}

- (void)setEditable:(BOOL)editable
{
    _editable = editable;
    if (editable == YES)
    {
        if (self.longPressGesture == nil)
        {
            self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureTrigger:)];
        }
        [self addGestureRecognizer:self.longPressGesture];
    }
    else
    {
        [self removeGestureRecognizer:self.longPressGesture];
    }
}

- (void)adjustContentSize
{
    if (self.growingAutomatic == YES)
    {
        if (self.collectionView.height != self.collectionView.contentSize.height)
        {
            self.height = self.collectionView.contentSize.height;
            self.collectionView.height = self.height;
            if ([self.delegate respondsToSelector:@selector(imagePreviewSizeChange:)])
            {
                [self.delegate imagePreviewSizeChange:self];
            }
        }
    }
}

#pragma mark - collection view delegate

- (BOOL)isTakeImageCellForIndex:(NSUInteger)index
{
    if (self.takeImageEnable == NO || self.limitImageNum == self.imageNum)
    {
        return NO;
    }
    return index == self.imageNum;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSUInteger itemNum = self.imageNum;
    if (self.takeImageEnable && itemNum < self.limitImageNum)
    {
        itemNum++;
    }
    return itemNum;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CImagePreviewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:IMAGE_CELL_REUSE_IDENTIFIER forIndexPath:indexPath];
    if ([self isTakeImageCellForIndex:indexPath.item])
    {
        cell.editing = NO;
//        if ([self.delegate respondsToSelector:@selector(takeImageViewForImagePreview:)])
//        {
//            UIView *takeImageView = [self.delegate takeImageViewForImagePreview:self];
//            takeImageView.frame = CGRectMake(0, 0, self.minImageSize.width, self.minImageSize.height);
//            cell.imageView.image = nil;
//            [cell.contentView addSubview:takeImageView];
//        }
//        else
//        {
            cell.imageView.image = [UIImage imageFromImage:[UIImage imageNamed:@"imagepicker_addphoto"] size:cell.imageView.size fillStyle:EImageFillStyleStretchByCenterScale];
//        }
    }
    else
    {
        cell.editing = self.isEditing;
        UIImage *image = [self.delegate imagePreview:self imageAtIndex:indexPath.item];
        if (image == nil)
        {
            image = [UIImage imageNamed:@"image_error"];
        }
        cell.imageView.image = [UIImage imageFromImage:image size:cell.imageView.size fillStyle:EImageFillStyleStretchByCenterScale];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self isTakeImageCellForIndex:indexPath.item])
    {
        if (self.isEditing == YES)
        {
            self.editing = NO;
        }
        if ([self.delegate respondsToSelector:@selector(didClickTakeImageViewOfImagePreview:)])
        {
            [self.delegate didClickTakeImageViewOfImagePreview:self];
        }
    }
    else
    {
        BOOL canDoNext = YES;
        if (self.editing == YES)
        {
            if ([self.delegate respondsToSelector:@selector(imagePreview:willDeleteImageAtIndex:)])
            {
                canDoNext = [self.delegate imagePreview:self willDeleteImageAtIndex:indexPath.item];
            }
            if (canDoNext)
            {
                [self deleteImageAtIndex:indexPath.item];
                if ([self.delegate respondsToSelector:@selector(imagePreview:didDeleteImageAtIndex:)])
                {
                    [self.delegate imagePreview:self didDeleteImageAtIndex:indexPath.item];
                }
            }
        }
        else
        {
            if ([self.delegate respondsToSelector:@selector(imagePreview:willShowImageAtIndex:)])
            {
                canDoNext = [self.delegate imagePreview:self willShowImageAtIndex:indexPath.item];
            }
            if (canDoNext)
            {
                [self showImageAtIndex:indexPath.item];
                if ([self.delegate respondsToSelector:@selector(imagePreview:didShowImageAtIndex:)])
                {
                    [self.delegate imagePreview:self didShowImageAtIndex:indexPath.item];
                }
            }
        }
    }
}

- (void)imageCollectionViewSizeChange:(CImageCollectionView *)imageCollectionView
{
    [self adjustContentSize];
}

#pragma mark - interface

- (void)setEditing:(BOOL)editing
{
    _editing = editing;
    for (NSUInteger i=0; i<self.imageNum; i++)
    {
        CImagePreviewCell *cell = (CImagePreviewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        if (cell != nil)
        {
            [cell setEditing:editing animated:YES];
        }
    }
}

- (void)longPressGestureTrigger:(UIGestureRecognizer *)gesture
{
    if (self.imageNum > 0 && gesture.state == UIGestureRecognizerStateBegan)
    {
        self.editing = !self.editing;
    }
}

- (CImagePreviewCell *)cellAtIndex:(NSUInteger)index
{
    if (self.imageNum == 0)
    {
        return nil;
    }
    return (CImagePreviewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
}

- (void)reloadImageAtIndex:(NSUInteger)index
{
    [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
}

- (void)insertImageAtIndex:(NSUInteger)index
{
    [self.collectionView performBatchUpdates:^{
        if (self.takeImageEnable == YES && self.limitImageNum == self.imageNum)
        {
            [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
        }
        [self.collectionView insertItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)insertImagesAtIndexes:(NSArray *)indexes
{
    [self.collectionView performBatchUpdates:^{
        if (self.takeImageEnable == YES && self.limitImageNum == self.imageNum)
        {
            [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:self.imageNum-indexes.count inSection:0]]];
        }
        NSMutableArray *indexPaths = [NSMutableArray array];
        for (NSNumber *number in indexes)
        {
            [indexPaths addObject:[NSIndexPath indexPathForItem:[number integerValue] inSection:0]];
        }
        [self.collectionView insertItemsAtIndexPaths:indexPaths];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)deleteImageAtIndex:(NSUInteger)index
{
    [self.collectionView performBatchUpdates:^{
        [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
        if (self.takeImageEnable == YES && self.limitImageNum-1 == self.imageNum)
        {
            [self.collectionView insertItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:self.imageNum inSection:0]]];
        }
    } completion:^(BOOL finished) {
        if (self.imageNum == 0)
        {
            self.editing = NO;
        }
    }];
}

- (void)showImageAtIndex:(NSUInteger)index
{
    if (self.imageBrowserView == nil)
    {
        self.imageBrowserView = [[[CImageBrowserView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds] autorelease];
        self.imageBrowserView.delegate = self;
    }
    
    CImagePreviewCell *cell = (CImagePreviewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    cell.hidden = YES;
    UIImage *image = [self.delegate imagePreview:self imageAtIndex:index];
    [self.imageBrowserView showWithAnchorView:cell.imageView image:image index:index fillStyle:EImageFillStyleStretchByCenterScale complete:^
    {
        cell.hidden = NO;
    }];
}

#pragma mark - CImageBrowseView delegate

- (void)imageBrowserViewNeedGetBack:(CImageBrowserView *)imageBrowserView
{
    CImagePreviewCell *cell = (CImagePreviewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:imageBrowserView.curImageIndex inSection:0]];
    cell.hidden = YES;
    [self.imageBrowserView dismissWithAnchorView:cell.imageView fillStyle:EImageFillStyleStretchByCenterScale complete:^
    {
        cell.hidden = NO;
        self.imageBrowserView = nil;
    }];
}

- (id)imageBrowserView:(CImageBrowserView *)imageBrowserView cellInfoAtIndex:(NSUInteger)index
{
    CImageBrowserViewCellInfo *info = [[[CImageBrowserViewCellInfo alloc] init] autorelease];
    info.image = [self.delegate imagePreview:self imageAtIndex:index];
    info.processing = NO;
    return info;
}

- (NSUInteger)numberOfImagesForImageBrowserView:(CImageBrowserView *)imageBrowserView
{
    return self.imageNum;
}

@end
